/*
 * SubServerOnDemandThread.java
 *
 * Created on August 23, 2006, 9:13 PM
 *
 */
package org.letva.copie.mainserver;

import java.net.*;
import java.io.*;
import org.letva.copie.common.message.SubServerInfo;
import org.letva.copie.common.message.Message;

/**
 *
 * @author Vuk Nikolic
 */
public class SubServerOnDemandThread extends Thread {

	/** Creates a new instance of SubServerOnDemandThread */
	public SubServerOnDemandThread(MainServer ms, SubServerInfo ssi) {
		super("SubServerOnDemandThread");
		myMainServer = ms;
		mySubServerInfo = ssi;
		myMainServer.writeLog("SubServerOnDemandThread created.");
	}

	@Override
	public void run() {
		myMainServer.writeLog("SubServerOnDemandThread: run started.");
		// cim smo dosli do ovde, znaci neki klijent na drugom racunaru je uradio
		// paste from ovog podservera, sto znaci da njemu treba da prosledim
		// moj Clipboard, odosno Clipboard mojih Clienata, ali posto sam na
		// ISTOJ MASINI to je moj sistemski klipbord.
		Object reply = null;
		boolean remove = true;

		try {
			String url = mySubServerInfo.getUrl().replaceAll("/", "");
			mySocket = new Socket(url, subServerOnDemandPort);

			// unutrasnji try je za proveru da li je doslo do neocekivanog
			// tipa (flavora) na klipboardu
			ObjectInput in = new ObjectInputStream(mySocket.getInputStream());
			reply = in.readObject();
			myMainServer.writeLog("SubServerOnDemandThread: subserver " + url + " is alive.");
			// dobili smo reply koja mora biti subServerInfo posto samo to salje
			// main server zato ga direktno dodajemo, a metoda je synchronized.

			myMainServer.addSubServer((SubServerInfo) ((Message) reply).getInfo());
			remove = false;

			in.close();
			mySocket.close();

			// ako se NIJE povezao ili doslo do nekog exception-a, proglasam
			// da je subserver mrtav i sklanjam ga iz liste subservera
			// necu da objavljujem izuzteke, posto ce se videti na listi
		} catch (UnknownHostException e) {
			remove = true;
		} catch (SocketException e) {
			remove = true;
		} catch (SocketTimeoutException e) {
			remove = true;
		} catch (IOException e) {
			remove = true;
		} catch (ClassNotFoundException ex) {
			remove = true;
		}

		if (remove == true) {
			myMainServer.removeSubServer(mySubServerInfo);
		}
		myMainServer.writeLog("SubServerOnDemandThread: finished.");
	}
	private Socket mySocket = null;
	private SubServerInfo mySubServerInfo = null;
	private int subServerOnDemandPort = 7773;
	private MainServer myMainServer = null;
}
